package net

import (
	"data-system/controller"
	"data-system/excel"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var Upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true // 允许跨域
	},
}

func Connection(c *gin.Context) {
	// 升级到WebSocket连接
	conn, err := Upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Println("连接升级失败:", err)
		return
	}
	// 创建客户端实例
	client := NewClient(conn)
	excel.Register(client.Id, client.Conn)
	go client.Start()
}

func Execute() {
	go excel.Start()
	router := gin.Default()
	router.GET("/", Connection)
	router.POST("/api/data/local/load", controller.LoadLocalAllData)
	router.GET("/api/data/nodeTypes", controller.LoadMenu)
	router.GET("/api/data/query/list", controller.QueryNodeTypeDataList)
	router.GET("/api/data/query/detail", controller.QueryNodeTypeDataDetail)
	router.POST("/api/data/op/save", controller.Save)
	router.POST("/api/data/op/delete", controller.Delete)

	router.POST("/api/resolve/conflict", controller.ResolveConflict)

	router.POST("/api/sync/todb", controller.ExcelToDB)
	router.POST("/api/sync/toexcel", controller.DBToExcel)

	router.GET("/api/enum/get", controller.Enum)

	router.POST("/api/assets", controller.GetAssets)

	router.GET("/api/config/get", controller.GetConfig)
	router.POST("/api/config/set", controller.SetConfig)

	err := router.Run("0.0.0.0:8082")
	if err != nil {
		log.Fatal("服务器启动失败")
		return
	}
}
